package com.sun.dream.fish.secret.asymmetry;

import javax.crypto.Cipher;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

public class RSAExample {
    private static final int KEY_SIZE = 2048; // RSA 密钥的长度

    public static void main(String[] args) throws Exception {
        String plainText = "Hello, World!";
        System.out.println("原始文本: " + plainText);

        // 生成 RSA 密钥对
        KeyPair keyPair = generateKeyPair();

        // 使用公钥进行加密
        String encryptedText = encrypt(plainText, keyPair.getPublic());
        System.out.println("加密后的文本: " + encryptedText);

        // 使用私钥进行解密
        String decryptedText = decrypt(encryptedText, keyPair.getPrivate());
        System.out.println("解密后的文本: " + decryptedText);
    }

    private static KeyPair generateKeyPair() throws NoSuchAlgorithmException {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(KEY_SIZE);
        return keyPairGenerator.generateKeyPair();
    }

    private static String encrypt(String plainText, PublicKey publicKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    private static String decrypt(String encryptedText, PrivateKey privateKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText));
        return new String(decryptedBytes);
    }

    private static String getBase64EncodedKey(Key key) {
        return Base64.getEncoder().encodeToString(key.getEncoded());
    }

    private static PublicKey getPublicKey(String base64EncodedKey) throws Exception {
        byte[] keyBytes = Base64.getDecoder().decode(base64EncodedKey);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return keyFactory.generatePublic(keySpec);
    }

    private static PrivateKey getPrivateKey(String base64EncodedKey) throws Exception {
        byte[] keyBytes = Base64.getDecoder().decode(base64EncodedKey);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return keyFactory.generatePrivate(keySpec);
    }
}